<?php
/**
 * Created by PhpStorm.
 * User:
 * Date:
 * Time:
 * 鉴权模块，密码采用服务端md5一次加密
 */

namespace ethink\acl;

use think\Db;
use think\Cookie;
use think\Request;
use think\Session;

/**
 * 鉴权模块
 * Class Auth
 * @package ethink\acl
 */
class Auth
{
    protected $dbPrefix;
    protected $options = null;
    public function __construct($options)
    {
        $this->options = $options;
        if("" == $this->options['db_prefix']){
            $this->dbPrefix = $this->options['db_prefix'];
        }else{
            $this->dbPrefix = $this->options['db_prefix'] . "_";
        }
    }

    /**
     * [checkAccountType description]
     * @param  [type] $account [description]
     * @return [type]          [description]
     */
    private function checkAccountType($account)
    {
        $accountType = null;
        if(preg_match("/^[a-zA-Z][a-zA-Z0-9_]*$/", $account)){
            $accountType = "account_name";
            trace("account type: user name, account: $account", "debug");
        }else if(preg_match("/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i", $account)){
            $accountType = "email";
            trace("account type: email, account: $account", "debug");
        }else if(preg_match('/^1\d{10}$/', $account)){
            $accountType = "phone_number";
            trace("account type: phone number, account: $account", "debug");
        }else{
            trace("unsupported account type: $account", "debug");
        }
        return $accountType;
    } 
 

     /**
     * 后台登录
     * @author lixd
     * @param $account string, openid
     * @return array|int, 
     */
    public function loginAdmin($account,$password)
    {
        //1登陆
        $accountObject = Db::table($this->dbPrefix. 'admin_users')
            ->whereOr('account', $account)
            ->whereOr('tel', $account)
            ->where('`password`', $password);
        $accountRecord = $accountObject
            ->field(['id', 'status','name','role_id','password'])
            ->find();
        // echo $account->getLastSql();exit;
        if(null == $accountRecord){//账号不存在
            trace("account [$account] does not exist", 'error');
            return 2001;
        }
        if(0 == $accountRecord['status']){//账号被禁用
            trace("account [$account] has been forbidden", 'debug');
            return 2002;
        }
        if($accountRecord['password']!=$password){
            trace("account [$account]password is error", 'debug');
            return 2015;   
        }
        $this->setData($accountRecord['id'],$account,'',$accountRecord['name'],$accountRecord['role_id']);
        return 0;
    }
 
    /**
     * [setData description]
     * @param [type] $userId [description]
     * @param [type] $openId [description]
     */
    public function setData($userId,$openId,$avatar='',$nick='',$roleId){
        $session_prefix = $this->options['session_prefix'];
        $data['userId'] = $userId;//记住userid
        $data['openId'] = $openId;//记住openid
        $data['avatar'] = $avatar;//记住avatar
        $data['nick'] = $nick;//记住nick
        $data['roleId'] = $roleId;
        $data['deadline'] = time() + $this->options['access_expires'];
        // var_dump($data);exit;
        Session::set($session_prefix.'_user', json_encode($data)); 
    }

    public function clearData($userId){
        $session_prefix = $this->options['session_prefix'];
        Session::set($session_prefix.'_user', '');         
    }
    /**
     * [getData description]
     * @return [type] [description]
     */
    public function getData(){
        $session_prefix = $this->options['session_prefix'];
        $data = Session::get($session_prefix.'_user');
        if($data){
            $data = json_decode($data,true);
            // var_dump($data);exit;
            if($data['deadline']<time()){
                return null;
            }
            else{
                //延长登陆时间
                $this->setData($data['userId'],$data['openId'],$data['avatar'],$data['nick'],$data['roleId']);
                return $data;
                
            }

        }
        else{
            return null;
        }
    }
  

}